package airport.server.DAO;

import airport.server.pojo.Hotel;
import airport.shared.beans.HotelBean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Kevin on 13/02/15.
 */
public class HotelDAO extends DAO<HotelBean> {

	@SuppressWarnings("unchecked")
	public ArrayList<HotelBean> selectAll() {
		List<Hotel> hotelList;
		ArrayList<HotelBean> hotelBeanList = new ArrayList<HotelBean>();
		Hotel hotel;

		connection();
		hotelList = session.createQuery("from Hotel").list();
		commitAndClose();

		Iterator i = hotelList.iterator();
		while (i.hasNext()) {
			hotel = (Hotel) i.next();
			hotelBeanList.add(pojoToBean(hotel));
		}

		return hotelBeanList;
	}

    public HotelBean select(Long id) {
        Hotel hotel;

        connection();
        hotel = (Hotel) session.createQuery("from Hotel h where h.idhotel = " + id + "").list().get(0);
        commitAndClose();

        return pojoToBean(hotel);
    }

	@Override
	public String save(HotelBean h) {
        connection();
        session.save(beanToPojo(h));
        commitAndClose();

		return "Hôtel enregistré";
	}

	@Override
	public String update(HotelBean h) {
		connection();
		session.update(beanToPojo(h));
		commitAndClose();

		return "Hôtel mis à jour";
	}

	@Override
	public String delete(HotelBean h) {
        connection();
        session.delete(beanToPojo(h));
        commitAndClose();

		return "Hôtel supprimé";
	}

	private HotelBean pojoToBean(Hotel hotel) {
		HotelBean hotelBean = new HotelBean();
        hotelBean.setIdhotel(hotel.getIdhotel());
        hotelBean.setNom(hotel.getNom());
		hotelBean.setAdresse(hotel.getAdresse());
		hotelBean.setStanding(hotel.getStanding());
		hotelBean.setTarif(hotel.getTarif());

        hotelBean.setPanneaux(hotel.getPanneau().size());


        return hotelBean;
    }

	private Hotel beanToPojo(HotelBean hotelBean) {
		Hotel hotel = new Hotel();
        hotel.setIdhotel(hotelBean.getIdhotel());
        hotel.setNom(hotelBean.getNom());
		hotel.setAdresse(hotelBean.getAdresse());
		hotel.setStanding(hotelBean.getStanding());
		hotel.setTarif(hotelBean.getTarif());

		return hotel;
	}
}
